<template>
  <div class="home">
    <el-form :inline="true" :model="query">
      <el-form-item>
        <!-- <el-date-picker type="year" v-model="query.year" placeholder="年份" /> -->
        <el-select v-model="query.year" placeholder="请选择">
          <template slot="prefix">
            <span style="padding: 5px; line-height: 25px; font-size: 15px">
              <i class="el-icon-date"></i>
            </span>
          </template>
          <el-option
            v-for="item in years"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="content">
      <CardBox title="" flexContent v-loading="loading1">
        <Card
          title="标的企业库数量"
          :number="countData.companyCount"
          suffix="个"
          :className="['red']"
          tips="标的企业库数量不会根据年限进行过滤"
        />
        <Card
          title="营业收入合计(可研口径)"
          :number="totalTypeData.valueList[0]"
          suffix="万元"
          :className="['blue']"
          :hover="true"
        >
          <template v-slot:hover>
            <div style="background: #fff; padding: 5px">
              <BusinessIncome :chartData="totalTypeData" />
            </div>
          </template>
        </Card>
        <Card
          title="项目数量合计"
          suffix="个"
          :number="countData.projectManageCount"
          :disabled="false"
          :className="['orange']"
          tips="项目数不会根据年限进行过滤"
        >
          <template>
            <div class="projectPop">
              <ul>
                <!-- <li>
                  <span>投前管理</span>
                  <span
                    ><span class="num">{{ countData.preInvestmentStage }}</span
                    >个</span
                  >
                </li> -->
                <li>
                  <span>立项审核</span
                  ><span
                    ><span class="num">{{
                      (countData.proposalStage || 0) +
                      (countData.auditStage || 0) +
                      (countData.biddingStage || 0) +
                      (countData.agreementSigningStage || 0)
                    }}</span
                    >个</span
                  >
                </li>
                <li>
                  <span>投后管理</span
                  ><span
                    ><span class="num">{{ countData.postInvestmentStage }}</span
                    >个</span
                  >
                </li>
              </ul>
            </div>
          </template>
        </Card>
        <Card
          title="机会跟踪"
          :number="countData.followCompanyCount"
          suffix="个"
          tips="机会跟踪不会根据年限进行过滤"
        />
        <Card
          title="净利润合计"
          :number="totalTypeData.valueList[1]"
          suffix="万元"
          :hover="true"
        >
          <template v-slot:hover>
            <div style="background: #fff; padding: 5px">
              <NetProfit :chartData="totalTypeData" />
            </div>
          </template>
        </Card>
        <Card
          title="投后重点跟进事项"
          :number="investmentCountData.total"
          suffix="个"
          :disabled="false"
          tips="跟进事项不会根据年限进行过滤"
        >
          <template>
            <div class="investmentPop">
              <ul>
                <li class="flex">
                  <span>跟进中</span>
                  <span
                    ><span class="num1">{{
                      investmentCountData.following
                    }}</span
                    >个</span
                  >
                </li>
                <li>
                  <span>已完成</span
                  ><span
                    ><span class="num1">{{ investmentCountData.done }}</span
                    >个</span
                  >
                </li>
              </ul>
            </div>
          </template></Card
        >
      </CardBox>
      <CardBox v-loading="loading2">
        <ChartTabs :operateData="operateData" :totalTypeData="totalTypeData" />
      </CardBox>
      <!-- <CardBox title="可研兑现情况" v-loading="loading3">
        <Table1 :tableData="operateData"></Table1>
      </CardBox> -->
      <CardBox title="体系导入情况" v-loading="loading4">
        <Table2 :tableData="projectManageData"></Table2>
      </CardBox>
      <CardBox title="投后重点跟进事项" v-loading="loading4">
        <Table3 :tableData="investmentDecisionData"></Table3>
      </CardBox>
      <!-- <CardBox title="月度经营数据（单位：万元）" v-loading="loading7">
        <Table5 :tableData="allOperateData"></Table5>
      </CardBox>
      <CardBox title="可研预测数据（单位：万元）" v-loading="loading7">
        <Table6 :tableData="table6Data"></Table6>
      </CardBox> -->
      <!-- <TableTabs :investmentDecisionData="investmentDecisionData" :afterInvestmentData="afterInvestmentData"></TableTabs> -->
      <!-- <CardBox title="投资决策跟进事项" v-loading="loading5">
        <Table3 :tableData="investmentDecisionData"></Table3>
      </CardBox>
      <CardBox title="待解决重点事项" v-loading="loading6">
        <Table4 :tableData="afterInvestmentData"></Table4>
      </CardBox> -->
    </div>
  </div>
</template>

<script>
import BusinessIncome from "./BusinessIncome.vue";
import NetProfit from "./NetProfit.vue";
import CardBox from "@/components/CardBox.vue";
import Card from "@/components/Card.vue";
import TableTabs from "@/views/TableTabs";
import ChartTabs from "@/views/ChartTabs";
import Table3 from "../TableTabs/Table3.vue";
import Table4 from "../TableTabs/Table4.vue";
import Table2 from "../TableTabs/Table2.vue";
import Table1 from "../TableTabs/Table1.vue";
import Table5 from '../TableTabs/Table5.vue';
import Table6 from '../TableTabs/Table6.vue'
export default {
  components: {
    CardBox,
    Card,
    TableTabs,
    ChartTabs,
    Table3,
    Table4,
    Table2,
    Table1,
    Table5,
    Table6,
    BusinessIncome,
    NetProfit,
  },
  data() {
    return {
      query: {
        year: (new Date().getFullYear()).toString(),
      },
      countData: {},
      operateData: [],
      projectManageData: [],
      investmentDecisionData: [],
      allOperateData: [],
      table6Data: [],
      investmentCountData: { done: 0, following: 0, total: 0 },
      afterInvestmentData: [],
      totalTypeData: {
        indexList: [],
        valueList: [],
      },
      years: [
        { value: "2022", label: "2022" },
        { value: "2023", label: "2023" },
      ],
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      loading5: false,
      loading6: false,
      loading7: false, //月度经营数据loading
      loading8: false, //可研预测数据
    };
  },
  mounted() {
    this.onSearch();
  },
  methods: {
    onSearch() {
      this.getCompnayCount();
      this.getOperateData();
      this.getProjectManage();
      this.getInvestmentDecision();
      this.getAfterInvestment();
      this.getTotalTypeData();
      this.getAllOperateData()
    },
    getYear() {
      return new Date(this.query.year).getFullYear();
    },
    async getOperateData() {
      this.loading3 = true;
      const res = await this.$apis.getOperateData({
        auth: 1,
        year: this.getYear(),
      });
      console.log("getOperateData", res);
      this.operateData = [...res.list] || [];
      this.loading3 = false;
    },
    groupByYearAndMonth(data) {
      const groups = {};
      for (const item of data) {
        const year = item.year;
        const month = item.month;
        if (!groups[year]) {
          groups[year] = {};
        }
        if (!groups[year][month]) {
          groups[year][month] = [];
        }
        groups[year][month].push(item);
      }
      return groups;
    },
    async getAllOperateData(){
      this.loading7 = true  
      const res =  await this.$apis.getAllOperateData({auth: 1})
      let data = [...res.list] || [];
      this.table6Data = data
      let allData = this.groupByYearAndMonth(data)
      this.allOperateData = this.handleAllData(allData)
      // this.allOperateData =  this.handleTable5Data(data)
      console.log('allOperateData-----',  this.allOperateData)
      this.loading7 = false
    },
    handleAllData(allData={}){
      console.log('allData------', allData)
      
      for(let yearKey in allData){
        let yearData = allData[yearKey]
        for(let monthKey in yearData){
          let netProfitTarget = 0;
          let businessIncomeTotalIndex = 0;
          let businessIncomeTotal = 0;
          let annualOperatingRevenueCompletionRate = 0;
          let netProfitTotalIndex=0;
          let netProfitTotal=0;
          let annualNetProfitCompletionRate=0;
          let monthData = yearData[monthKey]
          let totalObj = {}
          monthData.forEach((item)=>{
            netProfitTarget += parseInt(item.netProfitTarget)
            businessIncomeTotalIndex += parseInt(item.businessIncomeTotalIndex)
            businessIncomeTotal += parseInt(item.businessIncomeTotal)
            annualOperatingRevenueCompletionRate += parseInt(item.annualOperatingRevenueCompletionRate)
            netProfitTotalIndex += parseInt(item.netProfitTotalIndex)
            netProfitTotal += parseInt(item.netProfitTotal)
            annualNetProfitCompletionRate += parseInt(item.annualNetProfitCompletionRate)
          })
          console.log('monthData------>>>>', monthData)
          totalObj = {
                year: yearKey,
                month:monthKey,
                netProfitTarget:netProfitTarget,
                businessIncomeTotalIndex,
                businessIncomeTotal,
                annualOperatingRevenueCompletionRate,
                netProfitTotalIndex,
                netProfitTotal,
                annualNetProfitCompletionRate,
                project_name: '汇总'
          }
          monthData.push(totalObj)
        }
      }
      // console.log('处理后的allData', allData)
      let arr = []
      for(let yearKey in allData){
        let yearData = allData[yearKey]
        for(let monthKey in yearData){
          let monthData = yearData[monthKey]
          monthData.forEach((item)=>{
            arr.push(item)
          })
        }
      }
      console.log('处理后的月份列表', arr)
      return arr
    },
    handleTable5Data(tableData=[]) {
      // 对表格数据进行预处理，添加分组汇总行
      const processedData = [];
       /*
            year 
            month
            project    
            businessIncomeTotalIndex    
            businessIncomeTotal    
            annualOperatingRevenueCompletionRate    
            netProfitTotalIndex      
            netProfitTotal   
            annualNetProfitCompletionRate
        */ 
      let netProfitTarget = 0;
      let businessIncomeTotalIndex = 0;
      let businessIncomeTotal = 0;
      let annualOperatingRevenueCompletionRate = 0;
      let netProfitTotalIndex=0;
      let netProfitTotal=0;
      let annualNetProfitCompletionRate=0;
      for(let i=0; i< tableData.length;i++){
        let item = tableData[i]
        let nextItem = tableData[i+1]
        processedData.push(item)
        netProfitTarget += parseInt(item.netProfitTarget)
        businessIncomeTotalIndex += parseInt(item.businessIncomeTotalIndex)
        businessIncomeTotal += parseInt(item.businessIncomeTotal)
        annualOperatingRevenueCompletionRate += parseInt(item.annualOperatingRevenueCompletionRate)
        netProfitTotalIndex += parseInt(item.netProfitTotalIndex)
        netProfitTotal += parseInt(item.netProfitTotal)
        annualNetProfitCompletionRate += parseInt(item.annualNetProfitCompletionRate)
        if(nextItem){
          if(nextItem['year']!=item.year){
            processedData.push({
                year: item.year,
                month:item.month,
                netProfitTarget:netProfitTarget,
                businessIncomeTotalIndex,
                businessIncomeTotal,
                annualOperatingRevenueCompletionRate,
                netProfitTotalIndex,
                netProfitTotal,
                annualNetProfitCompletionRate,
                project_name: '汇总'
            })
             netProfitTarget = 0;
             businessIncomeTotalIndex = 0;
             businessIncomeTotal = 0;
             annualOperatingRevenueCompletionRate = 0;
             netProfitTotalIndex=0;
             netProfitTotal=0;
             annualNetProfitCompletionRate=0;
          } else {
            if(nextItem['month']!=item.month){
                processedData.push({
                  year: item.year,
                  month:item.month,
                  netProfitTarget,
                businessIncomeTotalIndex,
                businessIncomeTotal,
                annualOperatingRevenueCompletionRate,
                netProfitTotalIndex,
                netProfitTotal,
                annualNetProfitCompletionRate,
                project_name: '汇总'
              })
              netProfitTarget = 0;
              businessIncomeTotalIndex = 0;
              businessIncomeTotal = 0;
              annualOperatingRevenueCompletionRate = 0;
              netProfitTotalIndex=0;
              netProfitTotal=0;
              annualNetProfitCompletionRate=0;
            }
          }
        }else{
          processedData.push({
                year: item.year,
                month:item.month,
                netProfitTarget,
                businessIncomeTotalIndex,
                businessIncomeTotal,
                annualOperatingRevenueCompletionRate,
                netProfitTotalIndex,
                netProfitTotal,
                annualNetProfitCompletionRate,
                project_name: '汇总'
            })
            netProfitTarget = 0;
             businessIncomeTotalIndex = 0;
             businessIncomeTotal = 0;
             annualOperatingRevenueCompletionRate = 0;
             netProfitTotalIndex=0;
             netProfitTotal=0;
             annualNetProfitCompletionRate=0;
        }
        
        console.log('item-----',item)
      }

      // return this.tableData;
      return processedData
    },
    async getCompnayCount() {
      this.loading1 = true;
      const data = await this.$apis.getCompnayCount({ auth: 1 });
      this.countData = data.result || {};
      this.loading1 = false;
    },
    async getProjectManage() {
      this.loading4 = true;
      const res = await this.$apis.getProjectManage({
        auth: 1,
        year: this.getYear(),
      });
      this.projectManageData = [...res.list];
      this.loading4 = false;
    },
    async getInvestmentDecision() {
      this.loading5 = true;
      const res = await this.$apis.getInvestmentDecision({
        auth: 1,
        year: this.getYear(),
      });
      this.investmentDecisionData = [...res.list] || [];
      this.investmentCountData = res.count || {
        done: 0,
        following: 0,
        total: 0,
      };
      this.loading5 = false;
    },
    // 投后重点事项
    async getAfterInvestment() {
      this.loading6 = true;
      const res = await this.$apis.getAfterInvestment({
        auth: 1,
        year: this.getYear(),
      });
      this.afterInvestmentData = [...res.list] || [];
      this.loading6 = false;
    },

    async getTotalTypeData() {
      this.loading2 = true;
      const mothYear = await this.$apis.getMaxMonthByYear({
        auth: 1,
        year: this.getYear(),
        type: 1,
      });
      console.log("monthYear----------", mothYear);
      const totalTypeData = await this.$apis.getTotalTypeData({
        auth: 1,
        year: this.getYear(),
        month: mothYear || "",
        type: 1,
      });
      this.loading2 = false;
      this.totalTypeData = { ...totalTypeData };
    },
  },
};
</script>

<style lang="scss">
.home {
  padding: 10px;
  .projectPop {
    li {
      list-style: none;
      padding-right: 15px;
    }
    .num {
      font-size: 16px;
      font-weight: bold;
      color: #fff;
      margin-left: 20px;
    }
    .num1 {
      font-size: 16px;
      font-weight: bold;
      color: #000;
      margin-left: 20px;
    }
  }
  .investmentPop {
    height: 100%;
    ul {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    li {
      list-style: none;
      padding-right: 15px;
      text-align: right;
    }
    .num1 {
      font-size: 16px;
      font-weight: bold;
      color: #000;
      margin-left: 20px;
    }
  }
}
.el-form-item {
  margin-bottom: 0;
}
.flex {
  display: flex;
  justify-content: space-between;
}
</style>